package com.atguigu.gmall.task.scheduled;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.entity.GmallCorrelationData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 定时器
 */
@Component
@EnableScheduling //开启定时器注解
@Slf4j
public class ScheduledTask {


    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    //为了导入秒杀商品到Redis缓存中  （预热） 定时器  半夜12点
    //@Scheduled(cron = "* * 0 * * ?")
    @Scheduled(cron = "0/30 * * * * ?")
    public void task1(){
        //发个消息
        rabbitTemplate.convertAndSend(MqConst.EXCHANGE_DIRECT_TASK,MqConst.ROUTING_TASK_1,"");
    }




    //定时  半夜12点
    @Scheduled(cron = "* * 0 * * ?")
    //@Scheduled(cron = "0/30 * *  * * ?")
    public void task0(){
        //重新发送消息
        //五大数据类型  不需要Key值就能获取出来 重新发送  List  从左边放进去  从右边出来
        String json = (String) redisTemplate.opsForList().rightPop(MqConst.MQ_KEY_PREFIX);
        //交换机 队列、消息 次数
        GmallCorrelationData gmallCorrelationData = JSON.parseObject(json, GmallCorrelationData.class);
        int retryCount = gmallCorrelationData.getRetryCount();
        if(retryCount < MqConst.RETRY_COUNT){
            //重新发送
            gmallCorrelationData.setRetryCount(++retryCount);//更新次数
            rabbitTemplate.convertAndSend(gmallCorrelationData.getExchange(),
                    gmallCorrelationData.getRoutingKey(),gmallCorrelationData.getMessage(),gmallCorrelationData);
        }else{
            log.info("重新发送次数用尽");
        }

    }

}
